<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
    class
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <!-- <div class="title-gra plr30">
      <div class="grab gra-r">
        <span class="grab gra-l"></span>
      </div>
    </div> -->
    <div v-loading="loading" >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="菜单名称" prop="authorityName">
          <el-input v-model="ruleForm.authorityName"></el-input>
        </el-form-item>
        <el-form-item label="菜单URL" prop="authorityUrl">
          <el-input v-model="ruleForm.authorityUrl"></el-input>
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId" style="padding-left:10px">
          <el-tree
            style="height:220px;overflow:scroll;margin-left:-10px"
            :data="treeData"
            :props="defaultProps"
            node-key="authorityId"
            ref="tree"
            highlight-current
            accordion
            :default-expanded-keys="expandArray"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-form-item>
        <el-form-item label="菜单顺序" prop="authoritySort">
          <el-input v-model="ruleForm.authoritySort"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" placeholder="请输入描述" v-model="ruleForm.authorityDescription"></el-input>
        </el-form-item>
      </el-form>
      <div class="mr-btn" style="margin-right:2px">
        <el-button class="def-btn-sty" @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { findAllAuth, addAuth, updateAuth } from "@/api/menuApi.js";
import { queryAllauthority } from "@/api/authority.js";
export default {
  data() {
    return {
      dialogVisible: false,
      userId: "",
      title: "添加菜单",
      loading: false,
      defaultProps: {
        children: "children",
        label: "authorityName"
      },
      type: "",
      ruleForm: {},
      rules: {
        authorityName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        authoritySort: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        authorityUrl: [
          { required: true, message: "菜单URL不能为空", trigger: "blur" }
        ]
      },
      resultCode: 0,
      treeData: [],
      expandArray: []
    };
  },
  created() {},
  methods: {
    queryAllauthority() {
      queryAllauthority()
        .then(res => {
          this.treeData = this.toTree(res.sysAuthority, 0);
          if (this.type == "edit") {
            this.$nextTick(function() {
              this.$refs.tree.setCurrentKey(this.ruleForm.id);
            });
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    //递归处理数据成为树的数据
    toTree(data, pid) {
      var result = [],
        temp;
      for (var i = 0; i < data.length; i++) {
        if (data[i].parentId == pid) {
          result.push(data[i]);
          temp = this.toTree(data, data[i].authorityId);
          if (temp.length > 0) {
            data[i].children = temp;
          }
        }
      }
      return result;
    },
    openDialogVisible(type, val) {
      this.queryAllauthority();
      this.type = type;
      this.title = "添加菜单";
      if (type === "edit") {
        this.title = "编辑菜单";
        this.ruleForm = JSON.parse(JSON.stringify(val));
        this.$nextTick(function() {
          this.expandArray.push(val.id);
        });
      } else {
        this.ruleForm = {};
      }
      this.dialogVisible = true;
    },
    closeDialog() {
      this.treeData = [];
      this.expandArray = [];
      this.$refs["ruleForm"].resetFields();
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    getNotclick(arry) {
      if (
        arry.authorityId == this.ruleForm.id ||
        arry.parentId == this.ruleForm.id
      ) {
        return true;
      } else {
        if (arry.hasOwnProperty("children")) {
          for (let i = 0; i < arry.children.length; i++) {
            if (
              arry.children[i].authorityId == this.ruleForm.id ||
              arry.children[i].parentId == this.ruleForm.id
            ) {
              return true;
            } else {
              this.getNotclick(arry.children[i]);
            }
          }
        } else {
          return false;
        }
      }
    },
    handleNodeClick(data) {
      let flag = false;
      flag = this.getNotclick(data);
      if (flag) {
        this.$message.error("此菜单不可以作为父菜单");
        return false;
      }
      this.ruleForm.parentId = data.authorityId;
      this.ruleForm.authorityLevel = data.authorityLevel + 1;
    },
    save() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (
            this.ruleForm.authorityLevel == "" ||
            this.ruleForm.authorityLevel == undefined
          ) {
            this.ruleForm.parentId = 0;
            this.ruleForm.authorityLevel = 1;
          }
          console.log(this.ruleForm);
          if (this.type == "edit") {
            //修改菜单
            this.updateMenu();
          } else {
            this.addMenu();
          }
        } else {
          return false;
        }
      });
    },
    //添加菜单
    addMenu() {
      this.loading = true;
      addAuth(this.ruleForm)
        .then(res => {
          this.loading = false;
          if (res.data.success) {
            this.$message.success("注册成功");
            this.$emit("callBack");
            this.$refs["ruleForm"].resetFields();
            this.$refs["ruleForm"].clearValidate();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    //编辑菜单
    updateMenu() {
      this.loading = true;
      updateAuth(this.ruleForm)
        .then(res => {
          this.loading = false;
          if (res.data.success) {
            this.$message.success("修改成功");
            this.$emit("callBack");
            this.$refs["ruleForm"].resetFields();
            this.$refs["ruleForm"].clearValidate();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.loading = false;
        });
    }
  }
};
</script>

